package com.lekang.le.service.impl;

import java.util.*;

import com.lekang.common.core.domain.entity.SysRole;
import com.lekang.common.core.domain.entity.SysUser;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.le.domain.AccraditationRecord;
import com.lekang.le.domain.PendingTasks;
import com.lekang.le.mapper.AccraditationRecordMapper;
import com.lekang.le.service.IAccraditationRecordService;
import com.lekang.le.service.IPendingTasksService;
import com.lekang.system.mapper.SysRoleMapper;
import com.lekang.system.mapper.SysUserMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.le.mapper.CheckOutManagementMapper;
import com.lekang.le.domain.CheckOutManagement;
import com.lekang.le.service.ICheckOutManagementService;

/**
 * 退住办理Service业务层处理
 * 
 * @author caoyangyang
 * @date 2025-10-14
 */
@Service
public class CheckOutManagementServiceImpl implements ICheckOutManagementService 
{
    @Autowired
    private CheckOutManagementMapper checkOutManagementMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private IAccraditationRecordService accraditationRecordService;
    @Autowired
    private IPendingTasksService pendingTasksService;

    /**
     * 查询退住办理
     * 
     * @param id 退住办理主键
     * @return 退住办理
     */
    @Override
    public CheckOutManagement selectCheckOutManagementById(Long id)
    {
        return checkOutManagementMapper.selectCheckOutManagementById(id);
    }

    /**
     * 查询退住办理列表
     * 
     * @param checkOutManagement 退住办理
     * @return 退住办理
     */
    @Override
    public List<CheckOutManagement> selectCheckOutManagementList(CheckOutManagement checkOutManagement)
    {
        return checkOutManagementMapper.selectCheckOutManagementList(checkOutManagement);
    }

    /**
     * 新增退住办理
     * 
     * @param checkOutManagement 退住办理
     * @return 结果
     */
    @Override
    public Long insertCheckOutManagement(CheckOutManagement checkOutManagement)
    {
         //1、处理数据插入退住管理表中
         Random RANDOM = new Random();
         Integer re =  RANDOM.nextInt(9000) + 1000;
         checkOutManagement.setCheckOutNo("COUT"+re);
        checkOutManagement.setCreateTime(DateUtils.getNowDate());
        int i = checkOutManagementMapper.insertCheckOutManagement(checkOutManagement);
        List<CheckOutManagement> checkOutManagements = checkOutManagementMapper.selectCheckOutManagementList(checkOutManagement);
        Long checkOutManagementId = 0L;
        if(checkOutManagements.size()>0){
            checkOutManagementId = checkOutManagements.get(0).getId();
        }
        checkOutManagement.setBusinessId(checkOutManagementId.toString());
        //2、设置节点办理人
        Map map = new HashMap<>();
        map.put("assignee1",checkOutManagement.getCreator());
        SysUser currentSysUser = sysUserMapper.selectUserById(checkOutManagement.getCreator());//当前登陆人，申请人
        //3、根据当前用户的部门查询其所属部门中的护理长对象信息
        SysRole sysRole = new SysRole();
        sysRole.setRoleName("护理员组长");
        List<SysRole> sysRoles = sysRoleMapper.selectRoleList(sysRole);
        Long roleId = 0L;
        if(sysRoles.size()>0){
            roleId = sysRoles.get(0).getRoleId();
        }
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(200L);
        sysUser.setRoleId(roleId);
        SysUser nextUser = sysUserMapper.selectUserByUserRoleAndDept(sysUser);
        SysUser sysUser3 = new SysUser();
        SysRole sysRole3 = new SysRole();
        sysRole3.setRoleName("法务部员工");
        List<SysRole> sysRole3s = sysRoleMapper.selectRoleList(sysRole3);
        Long roleId3 = 0L;
        if(sysRole3s.size()>0){
            roleId3 = sysRole3s.get(0).getRoleId();
        }
        sysUser3.setRoleId(roleId3);
        sysUser3.setDeptId(200L);
        SysUser sysuser3 = sysUserMapper.selectUserByUserRoleAndDept(sysUser3);
        SysUser sysUser4 = new SysUser();
        SysRole sysRole4 = new SysRole();
        sysRole4.setRoleName("副院长");
        List<SysRole> sysRole4s = sysRoleMapper.selectRoleList(sysRole4);
        Long roleId4 = 0L;
        if(sysRole4s.size()>0){
            roleId4 = sysRole4s.get(0).getRoleId();
        }
        sysUser4.setRoleId(roleId4);
        sysUser4.setDeptId(200L);
        SysUser sysuser4 = sysUserMapper.selectUserByUserRoleAndDept(sysUser4);
//        SysUser sysUser5 = new SysUser();
//        SysRole sysRole5 = new SysRole();
//        sysRole5.setRoleName("结算组部长");
//        List<SysRole> sysRole5s = sysRoleMapper.selectRoleList(sysRole5);
//        Long roleId5 = 0L;
//        if(sysRole5s.size()>0){
//            roleId5 = sysRole5s.get(0).getRoleId();
//        }
//        sysUser5.setRoleId(roleId5);
//        sysUser5.setDeptId(200L);
//        SysUser sysuser5 = sysUserMapper.selectUserByUserRoleAndDept(sysUser5);
//        SysUser sysUser6 = new SysUser();
//        SysRole sysRole6 = new SysRole();
//        sysRole6.setRoleName("副院长");
//        List<SysRole> sysRole6s = sysRoleMapper.selectRoleList(sysRole6);
//        Long roleId6 = 0L;
//        if(sysRole6s.size()>0){
//            roleId6 = sysRole6s.get(0).getRoleId();
//        }
//        sysUser6.setRoleId(roleId6);
//        sysUser6.setDeptId(200L);
//        SysUser sysuser6 = sysUserMapper.selectUserByUserRoleAndDept(sysUser6);
        map.put("assignee2",nextUser.getUserId());
        map.put("assignee3",sysuser3.getUserId());
        map.put("assignee4",sysuser4.getUserId());
//        map.put("assignee5",sysuser5.getUserId());
//        map.put("assignee6",sysuser6.getUserId());
        map.put("assignee7",sysuser4.getUserId());

        // 4.创建流程实例绑定businessKey   qingjia:流程名   leaveRequest.getId().toString()：请假单业务id   map：动态参数
        System.out.println("创建任务得businessKey：：：：："+checkOutManagement.getBusinessId());
        runtimeService.startProcessInstanceByKey("tuizhu",checkOutManagement.getBusinessId(), map);
        //5、完成节点
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(checkOutManagement.getBusinessId())
                .processDefinitionKey("tuizhu")
                .taskAssignee(checkOutManagement.getCreator().toString()).singleResult();
        if(task!=null){
            taskService.complete(task.getId());
        }
        //6、保存审批记录
        AccraditationRecord record = new AccraditationRecord();
        record.setOpinion("同意");
        record.setType(2L);
        record.setFinishTime(new Date());
        record.setApproverId(checkOutManagement.getCreator());
        record.setApproverName(SecurityUtils.getUsername());
        record.setApproverNameRole(currentSysUser.getNickName());  // 需要你们自己查询
        record.setNextApproverId(nextUser.getUserId());
        record.setNextApprover(nextUser.getNickName());
        record.setNextApproverRole("护理员组长");
        record.setBussniessId(checkOutManagement.getId());
        record.setCurrentStep("发起申请-申请退住");
        record.setNextStep("审批-退住审批");
        record.setAuditStatus(1L);
        record.setStepNo(1L);
        record.setHandleType(1L);
        record.setCreateBy(checkOutManagement.getCreator().toString());
        record.setExtraField2(checkOutManagement.getElderlyId().toString());
        accraditationRecordService.insertAccraditationRecord(record);
        //7.保存我的申请
        PendingTasks pendingTasks = new PendingTasks();
        pendingTasks.setBussniessId(checkOutManagement.getId());
        pendingTasks.setTaskId(task.getId());
        pendingTasks.setTitle(checkOutManagement.getElderlyName()+"的退住申请");
        pendingTasks.setType(1L);
        pendingTasks.setAssignee(currentSysUser.getNickName());
        pendingTasks.setAssigneeId(currentSysUser.getUserId());
        pendingTasks.setStatus(2L);
        pendingTasks.setApplicationTime(checkOutManagement.getCreateTime());
        pendingTasks.setApplicat(currentSysUser.getNickName());
        pendingTasks.setApplicatId(currentSysUser.getUserId());
        pendingTasks.setFinishTime(new Date());
        pendingTasks.setIsHandle(1L);
        pendingTasks.setStepNo(2L);
        pendingTasks.setExtraField2(checkOutManagement.getElderlyId().toString());
        pendingTasksService.insertPendingTasks(pendingTasks);
        // 8.保存我的待办任务 -- 下一个人的待办任务
        // 查询工作流下一个任务节点id
        Task nextTask = taskService.createTaskQuery()
                .processInstanceBusinessKey(checkOutManagement.getId().toString())
                .processDefinitionKey("tuizhu")
                .taskAssignee(nextUser.getUserId().toString()).singleResult();
        PendingTasks pt = new PendingTasks();
        pt.setBussniessId(checkOutManagement.getId());
        pt.setTaskId(nextTask.getId());
        pt.setTitle(checkOutManagement.getElderlyName()+"的退住申请");
        pt.setType(1L);
        pt.setAssignee(nextUser.getNickName());
        pt.setAssigneeId(nextUser.getUserId());
//        System.out.println("Assignee::::::::"+pt.getAssignee());
//        System.out.println("AssigneeId:::::::"+pt.getAssigneeId());
        pt.setStatus(1L);
        pt.setApplicationTime(checkOutManagement.getCreateTime());
        pt.setApplicat(currentSysUser.getNickName());
        pt.setApplicatId(currentSysUser.getUserId());
        pt.setIsHandle(0L);
        pt.setStepNo(2L);
        pt.setExtraField2(checkOutManagement.getElderlyId().toString());
        pendingTasksService.insertPendingTasks(pt);
        return checkOutManagementId;
    }

    /**
     * 修改退住办理
     * 
     * @param checkOutManagement 退住办理
     * @return 结果
     */
    @Override
    public int updateCheckOutManagement(CheckOutManagement checkOutManagement)
    {
        checkOutManagement.setUpdateTime(DateUtils.getNowDate());
        return checkOutManagementMapper.updateCheckOutManagement(checkOutManagement);
    }

    /**
     * 批量删除退住办理
     * 
     * @param ids 需要删除的退住办理主键
     * @return 结果
     */
    @Override
    public int deleteCheckOutManagementByIds(Long[] ids)
    {
        return checkOutManagementMapper.deleteCheckOutManagementByIds(ids);
    }

    /**
     * 删除退住办理信息
     * 
     * @param id 退住办理主键
     * @return 结果
     */
    @Override
    public int deleteCheckOutManagementById(Long id)
    {
        return checkOutManagementMapper.deleteCheckOutManagementById(id);
    }
}
